package com.example.demo8.websocket;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.example.demo8.po.Chat;
import com.example.demo8.service.ChatService;
import com.example.demo8.util.SpringUtil;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/chat/{username}")
@Slf4j
public class WebSocketChat {

    public static Map<String, WebSocketChat> onlineMap = new ConcurrentHashMap<>();
    public static AtomicInteger onlineNum = new AtomicInteger(0);
    public Session session;

    public static void sendMessageToOne(Session targetSession, String message) throws IOException {
        targetSession.getBasicRemote().sendText(message);
    }

    private void sendOnlinePersonToAll() throws EncodeException, IOException {
        Set<String> usernameList = onlineMap.keySet();
        Set<Map.Entry<String, WebSocketChat>> entries = onlineMap.entrySet();
        for (Map.Entry<String, WebSocketChat> item : entries) {
            RespObj respObj = new RespObj();
            respObj.setType("open");
            respObj.setData(usernameList);
            item.getValue().session.getBasicRemote().sendText(JSONUtil.toJsonStr(respObj));
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) throws EncodeException, IOException {
        log.info("{} 上线了", username);
        this.session = session;
        incrOnlineNum();
        onlineMap.put(username, this);
        sendOnlinePersonToAll();
    }

    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) throws IOException {
        log.info("收到来自{} 的消息 -> {}", username, message);
        MessageObj messageObj = JSONUtil.toBean(message, MessageObj.class);
        String to = messageObj.getToUser();
        WebSocketChat webSocketChat = onlineMap.get(to);
        RespObj respObj = new RespObj();
        respObj.setData(messageObj);
        respObj.setType("message");
        // 发送给指定的用户
        sendMessageToOne(webSocketChat.session, JSONUtil.toJsonStr(respObj));
        // 持久化到数据库
        SpringUtil.getBean(ChatService.class).save(BeanUtil.toBean(messageObj, Chat.class));
    }

    @OnClose
    public void onClose(@PathParam("username") String username) throws EncodeException, IOException {
        log.info("{} 下线了", username);
        decrOnlineNum();
        onlineMap.remove(username);
        sendOnlinePersonToAll();
    }

    @OnError
    public void onError(Throwable throwable) {
        log.info("系统出现错误~");
        throwable.printStackTrace();
    }

    private void incrOnlineNum() {
        onlineNum.incrementAndGet();
    }

    private void decrOnlineNum() {
        onlineNum.decrementAndGet();
    }
}
